<?php


namespace app\admin\ctrl;


/**
 * 大数据导出
 */
class ExportCtrl
{
    /**
     * 导出百万级数据
     * 快速造数据：INSERT INTO hd_test (uname,age,city) SELECT uname,age,city FROM hd_test;
     * @return void
     */
    public function export() {
        //让程序一直运行
        set_time_limit(0);

        //设置程序运行内存
        ini_set('memory_limit', '128M');

        //导出文件名
        $fileName = '测试导出数据';
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');

        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));

        //添加导出标题
        fputcsv($fp, ['姓名', '年龄', '地区']);

        //链接数据库
        $dsn = "mysql:host=127.0.0.1;port=3306;dbname=db_www;charset=utf8";
        $pdo = new \PDO($dsn, 'root', env('database.password'));

        $total = 10000;
        $limit = 10000; //每次导出数量
        $pages = ceil($total / $limit);

        for($i = 0; $i < $pages; $i++) {
            $offset = $i * 10000;
            $sql = "SELECT uname,age,city FROM `hd_test` ORDER BY `id` LIMIT {$offset}, {$limit}";
            $stmt = $pdo->query($sql);
            $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
            foreach ($result as $item) {
                fputcsv($fp, $item);
            }
            //每1万条数据就刷新缓冲区
            ob_flush();
            flush();
        }
    }
}